package test;

import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

import org.jvnet.substance.SubstanceLookAndFeel;
import org.jvnet.substance.skin.GreenMagicSkin;

import com.kevin.model.db.DBTableModel;
import com.kevin.service.DBTabelService;
import com.kevin.service.impl.OracleTabelService;
import com.kevin.swing.CWCheckBoxRenderer;
import com.kevin.swing.CheckBoxCellEditor;
import com.kevin.swing.impl.WordSetDialog;
import com.kevin.util.ConfigProperties;
import com.kevin.util.JTableUtil;
import com.kevin.util.Utils;

//备份出来
public class CopyMainFrame extends JFrame {

    private static final long serialVersionUID = -1534907012085790087L;
    private JMenuBar mainBar = new JMenuBar();
    private JMenu sysMenu = new JMenu("系统");
    private JMenuItem exitItem = new JMenuItem("退出");
    private JMenuItem wordSetItem = new JMenuItem("分词设置");
    private JMenu aboutMenu = new JMenu("关于");
    private JMenuItem helpItem = new JMenuItem("帮助");

    private WordSetDialog panel = new WordSetDialog(null);

    private JPopupMenu popup = new JPopupMenu();
    private JMenuItem openfItem = new JMenuItem("生成实体类");

    private JTable contentTable;
    private DefaultTableModel defaultModel;
    private Object[][] playerInfo = new Object[][] { { "", false, "", "" } };
    private String[] names = { "序号", "选择", "表名", "数据量" };
    private int index = 0;
    private JScrollPane jspLogin;

    private JTable showSelectedTable;
    private DefaultTableModel showSelectedTableModel;
    private Object[][] showSelectedTablePlayerInfo = new Object[][] { { "", "" } };
    private String[] showSelectedTableNames = { "序号", "表名" };
    private JScrollPane showSelectedTableJSpane;

    private JTextArea logTA; // 日志输出
    private JScrollPane jsplogTA;

    private JLabel outDicLabel = new JLabel("输出目录：");
    private JTextField outDicText = new JTextField();// TextField 目录的路径
    private JButton outDicChooseBtn = new JButton("选择");// 选择
    private JFileChooser jfc = new JFileChooser();// 文件选择器

    private JLabel searchKeyLabel = new JLabel("关键字：");
    private JTextField searchText = new JTextField();// 搜素关键字
    private JButton searchBtn = new JButton("搜索表");// 选择
    private JCheckBox searchParticiple = new JCheckBox();// 分词
    private JLabel searchPartLabel = new JLabel("生成DAO");

    private JPanel btnPanel;
    private JPanel displayPanel;
//    private JButton dispalyBtn;
    private JButton preBtn;
    private JButton nextBtn;
    private SwingWorker<Long, Void> worker;
    private Boolean canStopSearch = false;

    private int searchNum = 0; // 搜索条目

    private DBTabelService dbTable2Model = new OracleTabelService();
    private List<DBTableModel> tableList = new ArrayList<DBTableModel>();
    private List<String> selectedTables = new ArrayList<String>(); // 选中的表名
    private int step = 0;

    public CopyMainFrame() {
        super("皮肤测试");
        setMainBar();
        setPanel();
        initFrame(600, 450);
    }

    private void initFrame(int frameWidth, int frameHeight) {
        setTitle("数据库表生成实体类");
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension screenDimension = tk.getScreenSize();
        int screenWidth = screenDimension.width;
        int screenHeight = screenDimension.height;
        setLocation((screenWidth - frameWidth) / 2, (screenHeight - frameHeight) / 2);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(frameWidth, frameHeight);
        setVisible(true);
    }

    private void setMainBar() {
        setJMenuBar(mainBar);
        mainBar.add(sysMenu);
        mainBar.add(aboutMenu);
        sysMenu.add(wordSetItem);
        sysMenu.addSeparator();
        sysMenu.add(exitItem);
        aboutMenu.add(helpItem);
        popup.add(openfItem);

        panel.setLocationRelativeTo(CopyMainFrame.this);
        panel.getWordSetTA().setText(ConfigProperties.getString(ConfigProperties.WORDSET, ""));
        panel.getOkbtn().addActionListener(e -> {
            String wordset = panel.getWordSetTA().getText();
            ConfigProperties.setProperty(ConfigProperties.WORDSET, wordset);
            if (!wordset.equals("")) {
            }
            panel.setVisible(false);
        });

        wordSetItem.addActionListener(e -> {
            panel.setVisible(true);
        });

        openfItem.addActionListener(e -> {
            if (outDicText.getText() != "") {
                openfile(outDicText.getText());
            }
        });
    }

    private void setPanel() {
        logTA = new JTextArea();
        logTA.setLineWrap(true);
        jsplogTA = new JScrollPane(logTA);
        initJTable();
        setTableColumWidth();
        addTableAction();

        jspLogin = new JScrollPane(contentTable);
        showSelectedTableJSpane = new JScrollPane(showSelectedTable);
        displayPanel = new JPanel();
        btnPanel = new JPanel();

        displayPanel.setLayout(new BorderLayout());
        displayPanel.add(jsplogTA, BorderLayout.CENTER);

        jspLogin.setPreferredSize(new Dimension(600, 69));
        showSelectedTableJSpane.setPreferredSize(new Dimension(600, 69));

        outDicText.setText(ConfigProperties.getString(ConfigProperties.DICTORY));
        outDicText.setPreferredSize(new Dimension(120, 20));
        searchParticiple.setSelected(true);

        addChooseOutDic();

        addSearchAction(); // 搜索表

        // 搜索触发事件
        addSearchTextListener();

        addStepPanel();// 上一步、下一步
        JPanel searchbtnPanel = new JPanel();
        searchbtnPanel.setLayout(new GridBagLayout());
        searchbtnPanel.add(outDicLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(0, 5, 0, 0), 0, 0));
        searchbtnPanel.add(outDicText, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
                new Insets(0, 0, 0, 0), 0, 0));
        searchbtnPanel.add(outDicChooseBtn, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(0, 0, 0, 0), 0, 0));
        searchbtnPanel.add(searchKeyLabel, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(0, 0, 0, 0), 0, 0));
        searchbtnPanel.add(searchText, new GridBagConstraints(4, 0, 2, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
                new Insets(0, 0, 0, 0), 0, 0));
        JPanel searchPanel = new JPanel();
        searchPanel.add(searchParticiple);
        searchPanel.add(searchPartLabel);
        searchPanel.add(searchBtn);
        searchbtnPanel.add(searchPanel, new GridBagConstraints(6, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(0, 0, 0, 0), 0, 0));

        add(searchbtnPanel, BorderLayout.NORTH);
        add(jspLogin, BorderLayout.CENTER);
        add(showSelectedTableJSpane, BorderLayout.SOUTH);
        add(displayPanel, BorderLayout.SOUTH);
    }

    /**
     * 
     * 输出文件选择
     * 
     * @Title addChooseOutDic
     * @author 吕凯
     * @date 2016年8月23日 下午3:22:58 void
     */
    private void addChooseOutDic() {
        outDicChooseBtn.addActionListener((e) -> {
            if (e.getSource().equals(outDicChooseBtn)) {// 判断触发方法的按钮是哪个
                    if (outDicText.getText() != "") {
                        File file = new File(outDicText.getText());
                        if (file.exists()) {
                            jfc.setCurrentDirectory(file);
                        }
                    }
                    jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);// 设定只能选择到文件夹
                    int state = jfc.showOpenDialog(null);// 此句是打开文件选择器界面的触发语句
                    if (state == 1) {
                        return;
                    } else {
                        File f = jfc.getSelectedFile();// f为选择到的目录
                        outDicText.setText(f.getAbsolutePath());
                        ConfigProperties.setProperty("dictory", f.getAbsolutePath());
                    }
                }
            }); // 添加事件处理
    }

    /**
     * 搜索表
     * 
     * @Title addSearchAction
     * @author 吕凯
     * @date 2016年8月23日 下午3:23:16 void
     */
    private void addSearchAction() {
        searchBtn.addActionListener(e -> {
            if (canStopSearch) {
                logTA.setText("正在停止搜索……");
                searchBtn.setEnabled(false);
            } else {
                // 搜索
                worker = new SwingWorker<Long, Void>() {

                    @Override
                    protected void done() {
                        searchDone();
                    }

                    @Override
                    protected Long doInBackground() throws Exception {
                        long ts = System.currentTimeMillis();
                        searchBtn.setText("停止");
                        canStopSearch = true;

                        resetSearchTable();
                        String searchkey = searchText.getText();
                        tableList = dbTable2Model.getTables(searchkey);
                        tableList.forEach(table -> addTableRow(table));

                        long te = System.currentTimeMillis();
                        logTA.setText("搜索到表" + tableList.size() + "条，共用时" + Utils.timeFormat(te - ts));
                        btnPanel.setVisible(true);
                        return null;
                    }

                };
                worker.execute();

            }
        }); // 添加事件处理
    }

    /**
     * 搜索时重置表格内容
     * 
     * @Title resetSearchTable
     * @author 吕凯
     * @date 2016年8月23日 下午3:56:29 void
     */
    private void resetSearchTable() {
        selectedTables.clear();
        playerInfo = new String[0][4];
        index = 0;
        defaultModel = new DefaultTableModel(playerInfo, names);
        contentTable.setModel(defaultModel);
        setTableColumWidth();
    }

    /**
     * 搜索表返回内容容器jtable初始化
     * 
     * @Title initJTable
     * @author 吕凯
     * @date 2016年8月23日 下午3:23:27 void
     */
    private void initJTable() {
        defaultModel = new DefaultTableModel(playerInfo, names);
        contentTable = new JTable(defaultModel) {
            private static final long serialVersionUID = 1234567L;

            // 不可编辑
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }

            @Override
            public Rectangle getCellRect(int row, int column, boolean includeSpacing) {
//                if (row % 2 == 1) {// 偶数行特殊处理合并
//                    Rectangle rect = new Rectangle(0, this.getRowHeight() * row, this.getWidth(), this.getRowHeight());
//
//                    // repaint();
//                    return rect;
//                }

                return super.getCellRect(row, column, includeSpacing);
            }

        };
        TableColumnModel tcm = contentTable.getColumnModel();
        tcm.getColumn(1).setCellEditor(new CheckBoxCellEditor());
        tcm.getColumn(1).setCellRenderer(new CWCheckBoxRenderer());
        // 添加标格监听事件
        contentTable.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    int columnIndex = contentTable.columnAtPoint(e.getPoint()); // 获取点击的列
                    int rowIndex = contentTable.rowAtPoint(e.getPoint()); // 获取点击的行

                    if (columnIndex == 1) {// 第0列时，执行代码
                        if (contentTable.getValueAt(rowIndex, columnIndex) == null) { // 如果未初始化，则设置为false
                            contentTable.setValueAt(false, rowIndex, columnIndex);
                        }

                        if (((Boolean) contentTable.getValueAt(rowIndex, columnIndex)).booleanValue()) { // 原来选中
                            contentTable.setValueAt(false, rowIndex, 1); // 点击后，取消选中
                            selectedTables.remove((String) contentTable.getValueAt(rowIndex, columnIndex + 1));
                        } else {// 原来未选中
                            contentTable.setValueAt(true, rowIndex, 1);
                            selectedTables.add((String) contentTable.getValueAt(rowIndex, columnIndex + 1));
                        }
                    }

                }
            }
        });
        contentTable.setRowHeight(20);
        showSelectedTableModel = new DefaultTableModel(showSelectedTablePlayerInfo, showSelectedTableNames);
        showSelectedTable = new JTable(showSelectedTableModel);// 显示选中的
        showSelectedTable.setRowHeight(20);
    }

    /**
     * 搜索输入框输入内容变化的监听方法
     * 
     * @Title addSearchActionListener
     * @author 吕凯
     * @date 2016年8月23日 下午3:21:00 void
     */
    private void addSearchTextListener() {
        searchText.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                textChange(e);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                textChange(e);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                textChange(e);

            }

            private void textChange(DocumentEvent e) {
                searchNum = 0;
                if (!tableList.isEmpty()) {
                    resetSearchTable();
                    if (searchText.getText().length() == 0) {
                        tableList.forEach(table -> addTableRow(table));
                        logTA.setText("搜索到表" + tableList.size() + "条");
                    } else {
                        String searchkey = searchText.getText();
                        tableList.stream().filter(table -> table.getTableName().toLowerCase().contains(searchkey)).forEach(table -> {
                            searchNum++;
                            DBTableModel tableShow = new DBTableModel();
                            tableShow.setTableName(table.getTableName());
                            tableShow.setDataSize(table.getDataSize());
                            addTableRow(tableShow);
                        });
                        if (searchNum == 0) {
                            btnPanel.setVisible(false);
                        } else {
                            btnPanel.setVisible(true);
                        }
                        logTA.setText("搜索到表" + searchNum + "条");
                    }
                }
                System.out.println("Event: " + e);
            }
        });
    }

    /**
     * 添加上一步、下一步Panel
     * 
     * @Title addStepPanel
     * @author 吕凯
     * @date 2016年8月23日 下午3:20:18 void
     */
    private void addStepPanel() {
        displayPanel.add(btnPanel, BorderLayout.SOUTH);

//        dispalyBtn = new JButton("123");
//        dispalyBtn.setHorizontalTextPosition(JLabel.RIGHT);
//        dispalyBtn.setText("显示10条");
//        dispalyBtn.setIcon(new ImageIcon(SysProperty.class.getResource("/").getPath() + "images/zip.png"));
//        dispalyBtn.setIconTextGap(JLabel.EAST);
//        btnPanel.add(dispalyBtn);
        preBtn = new JButton("上一步");
        nextBtn = new JButton("下一步");
        btnPanel.add(preBtn);
        btnPanel.add(nextBtn);
        preBtn.setVisible(false);
        btnPanel.setVisible(false);
        // 下一步
        nextBtn.addActionListener(e -> {
            step++;
            jsPaneStep();

        });
        // 上一步
        preBtn.addActionListener(e -> {
            step--;
            jsPaneStep();

        });
    }

    private void jsPaneStep() {
        if (step == 1) {
            index = 0;
            defaultModel = new DefaultTableModel(showSelectedTablePlayerInfo, showSelectedTableNames);
            contentTable.setModel(defaultModel);
            JTableUtil.fitTableColumns(contentTable, new int[] { 30, 400 });

            selectedTables.forEach(tableName -> {
                DBTableModel tableModel = new DBTableModel();
                tableModel.setTableName(tableName);
                addTableRow(tableModel, 1);
            });
            preBtn.setVisible(true);
            logTA.setText("共选中" + selectedTables.size() + "个表");
        } else if (step == 2) {
            nextBtn.setVisible(false);
            preBtn.setVisible(true);
        } else if (step == 0) { // 第一步
            resetSearchTable();
            tableList.forEach(tableName -> {
                DBTableModel tableModel = new DBTableModel();
                tableModel.setTableName(tableName.getTableName());
                tableModel.setDataSize(tableName.getDataSize());
                addTableRow(tableModel);
            });
            logTA.setText("共选中" + tableList.size() + "个表");
            preBtn.setVisible(false);
            nextBtn.setVisible(true);
        }
    }

    /**
     * 设置表格宽度
     * 
     * @Title setTableColumWidth
     * @author 吕凯
     * @date 2016年8月23日 下午4:07:46 void
     */
    private void setTableColumWidth() {
        JTableUtil.fitTableColumns(contentTable, new int[] { 30, 30, 400, 80 });
        TableColumnModel tcm = contentTable.getColumnModel();
        tcm.getColumn(1).setCellEditor(new CheckBoxCellEditor());
        tcm.getColumn(1).setCellRenderer(new CWCheckBoxRenderer());
        JTableUtil.fitTableColumns(showSelectedTable, new int[] { 30, 400 });
    }

    public void searchDone() {
        searchBtn.setText("搜索表");
        canStopSearch = false;
        searchBtn.setEnabled(true);
    }

    public void addTableRow(DBTableModel table, int type) {
        if (type == 0) {// 搜索表
            defaultModel.addRow(new Object[] { (++index) + "", new Boolean(false), table.getTableName(), table.getDataSize() + "" });

        } else if (type == 1) { // 选中表
            defaultModel.addRow(new Object[] { (++index) + "", table.getTableName() });

        }
//        defaultModel.addRow(new String[] { "" }); // 空行
    }

    public void addTableRow(DBTableModel table) {
        addTableRow(table, 0);
    }

    /**
     * 添加table事件
     */
    private void addTableAction() {
        contentTable.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger())
                    showMenu(e);
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger())
                    showMenu(e);
            }

            private void showMenu(MouseEvent e) {
//                int row = e.getY() / contentTable.getRowHeight();
//                filename = "fileName";
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        });

        // 监听事件
//        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
//            public void valueChanged(ListSelectionEvent e) {
//                if (e.getValueIsAdjusting()) {// 连续操作
//                    int columnIndex = table.getSelectedColumn();
//                    int rowIndex = table.getSelectedRow();
//                    if (columnIndex == 1) {
//                        filename =searchModel.getSearchPdfs().get(rowIndex/2).getAbsolatePath();
//                        System.out.println("正在打开文件 " + filename);
//                        openfile(filename);
//                    }
//                }
//            }
//        });
    }

    private void openfile(String filename) {
        try {
            Desktop.getDesktop().open(new File(filename));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    public void showlog(String log) {
        logTA.setText(log);
    }

    /**
     * 隐藏步骤
     * 
     * @Title showBtnJPanel
     * @author 吕凯
     * @date 2016年8月24日 上午9:04:08 void
     */
    public void showStep() {
        btnPanel.setVisible(true);
    }

    /**
     * 显示步骤
     * 
     * @Title hideBtnJPanel
     * @author 吕凯
     * @date 2016年8月24日 上午9:04:25 void
     */
    public void hideStep() {
        btnPanel.setVisible(false);
    }

    public JButton getBtnsearch() {
        return searchBtn;
    }

    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        System.out.println(UIManager.getSystemLookAndFeelClassName());
        try {
            SwingUtilities.invokeLater(new Runnable() {// 5.3及以后 多两个jar包
                        @Override
                        public void run() {

                            try {
                                SubstanceLookAndFeel.setSkin(new GreenMagicSkin());
                            } catch (Exception e) {
                                // e.printStackTrace();
                            }
                        }

                    });
//    UIManager.setLookAndFeel(new SubstanceGreenMagicLookAndFeel());// 旧版去除两jar包
        } catch (Exception e) {
            System.out.println("Substance Raven Graphite failed to initialize");
        }
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CopyMainFrame w = new CopyMainFrame();
                w.setVisible(true);
            }
        });
    }
}
